#include <stdlib.h> //for atoi
#include <string.h>
#include "hdf_io_service.h"
#include "hdf_sbuf.h"
#include "hdf_log.h"

static struct HdfIoService *g_ptzService = NULL;
const char *DRIVER_SERVICE_NAME = "ptz_service";

void Usage(void) {
    printf("\nUsage：\n");
    printf("\tptz_app cmd H/V [-]number\n");
    printf("\tcmd support following:\n");
    printf("\t\trotate: 旋转指定角度\n");
    printf("\t\tset-speed: 设置旋转速度\n");
    printf("\teg:ptz_app rotate H -30\n\n");
}

enum MotorID {
    H_MOTOR = 0,
    V_MOTOR
};

int getCmdIDByName(const char *cmd) {
    if(strcmp(cmd, "rotate") == 0) {
        return 0;
    }
    
    if(strcmp(cmd, "set-speed") == 0) {
        return 1;
    }

    return -1;

}
int main(int argc, char **argv)
{
    if(argc < 3) {
        Usage();
        return -1;
    }

    g_ptzService = HdfIoServiceBind(DRIVER_SERVICE_NAME, 0);
    if (g_ptzService == NULL || g_ptzService->dispatcher == NULL || g_ptzService->dispatcher->Dispatch == NULL) {
        HDF_LOGE("%s:bad remote service found!", __func__);
        return HDF_FAILURE;
    }

    enum MotorID motor = H_MOTOR;
    if(argv[2][0] == 'H') {
        motor = H_MOTOR;
    } else if(argv[2][0] == 'V') {
        motor = V_MOTOR;
    } else {
        Usage();
        return -1;
    }
    int16_t value = atoi(argv[3]);

    struct HdfSBuf *data = HdfSBufObtainDefaultSize();
    HdfSbufWriteUint8(data,(int8_t)motor);
    HdfSbufWriteInt16(data, value);

    HDF_LOGE("%s:cmd %s[%d] %d motor %d degrees", __func__, argv[1], getCmdIDByName(argv[1]), motor, value);

    g_ptzService->dispatcher->Dispatch(&g_ptzService->object, getCmdIDByName(argv[1]), data, NULL);

    HdfSBufRecycle(data);

    HdfIoServiceRecycle(g_ptzService);

    printf("ptz task done.\n");
    return 0;
}